<template>
  <div class="areaContainer">
    <div class="search">
      <el-input v-model.trim="searchValue" placeholder="请输入区域位置关键字进行查询" clearable :prefix-icon="Search" @keyup="getVolationList(searchValue)">
        <template #append>
          <el-button :icon="Search"  @click="getVolationList(searchValue)"/>
        </template>
      </el-input>
      <el-button style="margin-left: 30px;" type="primary" @click="addVolationVisable = true">添加违规单</el-button>
      <el-dialog v-model="addVolationVisable" title="添加违规单" width="30%" draggable>
        <el-form v-model="addVolationForm" label-position="right">
          <el-form-item prop="carId" label="违规车辆ID">
            <el-input v-model="addVolationForm.carId" placeholder="请输入车辆ID"  width="150"/>
          </el-form-item>
          <el-form-item prop="message"  width="100" label="违规信息">
            <el-input v-model="addVolationForm.message" placeholder="请输入违规信息"  width="150"/>
          </el-form-item>
          <el-form-item prop="detail"  width="100" label="处理方式">
            <el-input v-model="addVolationForm.detail" placeholder="请输入处理方式"  width="150"/>
          </el-form-item>
           <el-form-item prop="imagUrl"  width="100" label="违规图片记录">
            <el-upload class="avatar-uploader" action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15" :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
              <img v-if="imageUrl" :src="imageUrl" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="addVolationVisable = false">取消</el-button>
            <el-button type="primary" @click="addVolation()">确认</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
    <el-table :data="volationData" stripe style="width: 100%;margin-top: 10px;" height="50%"  :default-sort="{ prop: 'createTime', order: 'descending' }">
    <el-table-column prop="vioId" label="违规ID"/>
    <el-table-column prop="carId" label="违规车辆ID" />
    <el-table-column prop="message" label="违规信息"/>
    <el-table-column label="是否已处理" >
        <template #default="row">
            <el-button v-if="row.row.processed === 0" type="danger">未处理</el-button>
            <el-button v-else type="success">已处理</el-button>
        </template>
    </el-table-column>
    <el-table-column label="图片" >
        <template #default="row">
            <el-image :src="row.row.imagUrl" style="height: 50px"/>
        </template>
    </el-table-column>
    <el-table-column prop="detail" label="处理措施"/>
    <el-table-column prop="createTime" label="创建时间" sortable>
      <template #default="row">
        <div>{{timeTuTIL.myTimeFormat(row.row.createTime)}}</div>
      </template>
    </el-table-column>
    <el-table-column fixed="right" label="操作" width="130">
      <template #default="row">
          <el-tooltip content="编辑" placement="bottom">
            <el-button link type="primary" :icon="Edit"  class="myLink" @click="clickEditHandler(row)" />
          </el-tooltip>
          <el-tooltip content="删除" placement="bottom">
            <el-button link type="danger" :icon="Delete"  class="myLink" @click="volationDelete(row)"></el-button>
          </el-tooltip>
      </template>
    </el-table-column>
  </el-table>
  <el-dialog v-model="editVolationVisible" title="编辑" draggable>
    <el-form :model="editVolationForm" label-width="80px">
      <el-form-item label="违规ID" prop="vioId">
        <el-input v-model="editVolationForm.vioId" autocomplete="off" disabled/>
      </el-form-item>
      <el-form-item label="违规车辆" prop="carId">
        <el-input v-model="editVolationForm.carId" autocomplete="off" />
      </el-form-item>
      <el-form-item label="违规信息" prop="messsge">
        <el-input v-model="editVolationForm.messsge" autocomplete="off" />
      </el-form-item>
      <el-form-item label="处理措施" prop="detail">
        <el-input v-model="editVolationForm.detail" autocomplete="off"/>
      </el-form-item>
      <el-form-item label="是否已处理" prop="processed">
        <el-input v-model="editVolationForm.processed" autocomplete="off" disabled/>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="editVolationVisible = false">取消</el-button>
        <el-button type="primary" @click="volationEdit()">提交修改</el-button>
      </span>
    </template>
  </el-dialog>
     <div class="pagination">
       <el-pagination v-model:current-page="page" v-model:page-size="size" :page-sizes="[5,10,20,30]" :small="small" :disabled="disabled"
      :background="background" layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange"/>
  </div>
  </div>
</template>

<script setup>
import { reactive , inject , onMounted , ref } from "vue"
import axios from '../../axios/axiosInstance'
import timeTuTIL from '../../utils/timeUtilT'
import { ElLoading,ElMessage ,ElMessageBox} from 'element-plus'
import { Delete ,Edit,Search,Plus} from '@element-plus/icons-vue'

//变量定义

let editVolationVisible = ref(false)
let addVolationVisable = ref(false)
let volationData = reactive([])
let nameFilter = reactive([])
let categoryNameFilter = reactive([])
let searchValue = ref()
let editVolationForm = reactive({
  vioId: 0,
  carId: '',
  message: '',
  processed: 0,
  detail: '',
})

let addVolationForm = reactive({
  carId: '',
  message: '',
  imagUrl: '',
  detail: '',
})
let total = ref(0)
let page = 1
let size = 5
const small = ref(false)
const background = ref(false)
const disabled = ref(false)
const imageUrl = ref('')

//方法 

const handleAvatarSuccess = (response,uploadFile) => {
  imageUrl.value = URL.createObjectURL(uploadFile.raw)
}

const beforeAvatarUpload = (rawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('Avatar picture must be JPG format!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('Avatar picture size can not exceed 2MB!')
    return false
  }
  return true
}

const handleSizeChange = (val) => {
  console.log(`${val} items per page`)
  size = val
  init()
}
const handleCurrentChange = (val) => {
  console.log(`current page: ${val}`)
  page = val
  init()
}

 const clear = (value) => {
    Object.keys(value).map(key => {
      delete value[key]
    })
  }

const getVolationList = (searchValue) => {
  if(searchValue != ''){
    axios.get(`/parking-service/area/areaList/${searchValue}`).then((res) => {
        console.log(res)    
        if(res.code == 200){
          clear(volationData)
          for(let i in res.data){
            console.log(i)
            volationData.push(res.data[i])
          }
          ElMessage({type: "success",message: "查询成功"});
        }else{
          ElMessage({type: "error",message: "查询失败"});
       }
      }).catch((err) => {
        console.log(err)
      })
  }else{
    init()
  }
}
const filterHandler1 = (value,row,column) => {
  const property = column['property']
  return row[property] === value
}

const filterHandler2 = (value,row,column) => {
  const property = column['property']
  return row[property] === value
}

const addVolation = () =>{
  //向后端发送请求
   axios.post('/parking-service/area/addArea/',addVolationForm).then((res) => {   
      console.log("res为：")
      console.log(res)
      if(res.code == 200){
          //添加停车区域成功
          ElMessage({type: "success",message: "添加成功"});
          volationData.push(res.data)
        }else{
          //添加失败
         ElMessage({type: "error",message: "添加失败"})
        }
    
    }).catch((err) => {

      console.log(err)

    })

}

const clickEditHandler = (row) => {
  editVolationVisible.value = true;
  console.log("row为：")
  console.log(row)
  editVolationForm.vioId = row.row.vioId;
  editVolationForm.carId = row.row.carId;
  editVolationForm.message = row.row.message;
  editVolationForm.processed = row.row.processed;
  editVolationForm.detail = row.row.detail;
  console.log(editVolationForm)
}

const volationEdit = (row) => {
   axios.delete('/record-service/violation/update',editVolationForm).then((res) => {
    console.log(res)
    if(res.code == 200){
      ElMessage({type: "success",message: "删除成功"});
      volationData.pop(row.$index)
    }else{
      ElMessage({type: "error",message: "删除失败"});
    }
  }).catch((err) => {
    console.log(err)
  })
}

const volationDelete = (row) => {
  console.log("删除的row为：")
  console.log(row)
  let vioId = row.row.vioId
  ElMessageBox.confirm(
    '确定要删除违规记录'+vioId+'吗？',
    'Warning',
    {
      confirmButtonText: 'OK',
      cancelButtonText: 'Cancel',
      type: 'warning',
    }
  )
    .then(() => {
      let vioId = row.row.vioId;
      console.log(vioId)
      axios.delete('/record-service/violation/delete/'+vioId).then((res) => {
        console.log(res)
        if(res.code == 200){
          ElMessage({type: "success",message: "删除成功"});
          volationData.pop(row.$index)
        }else{
          ElMessage({type: "error",message: "删除失败"});
       }
      }).catch((err) => {
        console.log(err)
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '删除取消',
      })
    }) 
}

const init = () => {
  const loading = ElLoading.service({
        lock: true,
        text: '拼命加载中',
          background: 'rgba(0, 0, 0, 0.7)',
      })
      setTimeout(() => {
        loading.close()
      }, 2000)
     axios.get(`/record-service/violation/allList/${page}/${size}`).then((res) => {   
      console.log("res为：")
      console.log(res)
      clear(volationData)
      total.value = res.data.total
      for(let i in res.data.content){
        console.log(i)
        volationData.push(res.data.content[i])
      }
      console.log("最后的areaData是：")
      console.log(volationData)
    }).catch((err) => {

      console.log(err)

    })
}


//页面初始化方法
onMounted(()=>{ 
  init()
})
</script>

<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
.areaContainer .search{
  display: flex;
  width: 600px;
}
.areaContainer .pagination{
 justify-content: center;
 margin-top: 15px;
}

</style>
